/**
 * Created by Jason on 2017-06-12.
 */
$(document).ready(function() {
    //验证初始化
    ko.validation.init({
        errorElementClass: 'has-error',
        insertMessages: false
    });

    var apiUrl = {
        getJiziUrl: "/weixin/api.jizi/getpost",
        joinUrl: "/activity/api.freezi/joinPost",
        getSignUrl: "/activity/api.freezi/getSignPost",
        supportUrl: "/activity/api.freezi/supportPost",
        shareUrl: "/activity/api.freezi/sharePost",
        advPost: "/activity/api.freezi/listAdvPost",
        checkPost: "/activity/api.freezi/clickAdvPost"  //爱心企业点击记录
    };

    var indexViewModel = function() {
        var self = this;
        self.sign_id = ko.observable(parseInt(signId));
        self.activity_id = ko.observable(parseInt(activity.id));
        self.address = ko.observable('福建省 厦门市 思明区');
        self.school = ko.observable('');

        self.kerRules = ko.observable(false); //当前tab状态不是活动说明

        self.flag = ko.observable(false);
        self.showHelpAreaFlag = ko.observable(false);
        self.refresh = ko.observable(0);
        self.isSign = ko.observable(false);
        self.isSupport = ko.observable(0);
        activity.extend_info = JSON.parse(activity.extend_info);
        self.activity = ko.observable(activity);
        self.imageNum = ko.observable(0);
        self.imageTotal = ko.observable(39);
        self.shareDefine = ko.observable(JSON.parse(activity.share_define));
        self.writeText = ko.observable('我也要报名');
        self.helpText = ko.observable('帮自己加一笔');
        self.sign = ko.observable(null);
        self.selfSigner = ko.observable('');
        self.countDown = ko.observable("正在加倍计算中...");
        self.lookMore = ko.observable(true);
        self.lookMore1 = ko.observable(true);
        self.lookInfo = ko.observable(false);
        self.listAdv = ko.observableArray([]);

        self.grade = ko.observable('');
        self.gradeList = ko.observableArray([
           '中小班', '大班', '一年级', '二年级', '三年级', '四年级', '五年级', '六年级', '初一', '初一以上', '成人'
        ]);

        self.username = ko.observable('').extend({
            required : {
                params : true,
                message : '用户名不能为空'
            },
            minLength : {
                params : 1,
                message : '用户名长度长度为1-10个字符'
            },
            maxLength : {
                params : 10,
                message : '用户名长度长度为1-10个字符'
            }
        });
        self.mobile = ko.observable('').extend({
            required: {
                params: true,
                message: '请输入手机号'
            },
            validation: {
                validator: function(v){
                    return $.validator.checkPhone(v);
                },
                message: '手机号格式错误'
            }
        });
        self.field1 = ko.observable('').extend({
            required: {
                params: true,
                message: '信息未完整'
            }
        });
        self.field2 = ko.observable('').extend({
            required: {
                params: true,
                message: '信息未完整'
            }
        });
        self.field3 = ko.observable('').extend({
            required: {
                params: true,
                message: '信息未完整'
            }
        });
        self.lMore = function () {
          self.lookMore(!self.lookMore());
        };
        self.lMore1 = function (index) {
            // var list = self.info();
            // self.info([]);
            // list.forEach(function (element, index1) {
            //     if(index == index1) {
            //         element.ismore = !element.ismore;
            //     }
            //     self.info.push(element);
            // });
            if(index == 1) {
                self.ismore1(!self.ismore1());
            }else {
                self.ismore(!self.ismore());
            }

        };

        self.lInfo = function () {
            self.lookInfo(!self.lookInfo());
        };

        // 修改kertab
        self.KerTab = function (type) {
          if(type == 'rules') {
              self.kerRules(true);
          }else {
              self.kerRules(false);
          }
        };

        //倒计时
        var countDownInt;
        self.getCountDown = function (begin, end){
            clearInterval(countDownInt);
            countDownInt = setInterval(function(){
                //结束时间和当前的时间差
                var t = end - unix_timestamp;
                var d = Math.floor(t/60/60/24);

                var hour = Math.floor(t/60/60%24);
                var min = Math.floor(t/60%60);
                var sec = Math.floor(t%60);

                if (hour < 10) {
                    hour = "0" + hour;
                }
                if (min < 10) {
                    min = "0" + min;
                }
                if (sec < 10) {
                    sec = "0" + sec;
                }

                if(unix_timestamp < begin){
                    self.countDown('活动还未开始');
                }else{
                    if(t <= 0){
                        self.countDown('活动已结束');
                    }else{
                        self.countDown(d+'天'+hour+'时'+min+'分'+sec+'秒');
                    }
                }
                unix_timestamp++;
            },1000);
        };

        //初始选择学校
        self.schoolInit = function (data) {
            $('.wrap-grade').empty();
            $('.wrap-grade').html('<input type="text" id=\'school\' data-bind="value: school"/>');
            $("#grade").picker({
                title: "请选择练字学校",
                cols: [
                    {
                        textAlign: 'center',
                        values: data
                    }
                ]
            });
        };

        //显示支持记录
        self.showSupportLog = function(data){
            return ''+data.extend_info.number+ '笔';
        };
        //显示支持记录
        self.showSupport = function(data){
            return '完成了'+ data.support_num+ '笔';
        };

        self.openModal = function() {
            if(self.isSign()) {
                if(self.sign().openid != weixin_user.openid && self.selfSigner()) {
                    $.toast('您已报过名', 'forbidden', function() {
                        window.location.href = "/activity/freezi/index/activity_id/" + self.sign().activity_id + "/sign_id/" + self.selfSigner().id;
                    });
                }else {
                    $.alert('您已报过名，邀请更多的小伙伴帮你完成写字吧！！！', function() {
                        //$.showShareDialog();
                    });
                }
                return false;
            }else {
                if(self.countDown() == '活动还未开始'){
                    $.toast("活动还未开始","forbidden");
                    return;
                }
                if(self.countDown() == '活动已结束'){
                    $.toast("活动已结束","forbidden");
                    return;
                }
                window.location.href = "/activity/freezi/signdetail?activity_id=" + self.activity_id() + '&sign_id=0&music=' + self.activity().music;
            }

        };

        self.isShowAdd = function() {
            if(signId && !self.isSupport() && self.imageNum() < self.imageTotal()) {
                return true;
            }

            return false;
        };
        self.isShowWant = function() {
            if(!signId || self.isSupport() || self.imageNum() >= self.imageTotal()) {
                if(self.imageNum() >= self.imageTotal()) {
                    self.writeText('笔画已集齐,我也来参与!');
                }
                return true;
            }

            return false;
        };
        // 解决ios音乐无法自动播放
        self.iosMusicPlay = function(){
            wx.ready(function() {
                var globalAudio=document.getElementById("bgMusic");
                globalAudio.play();
            });
        };
        self.musicPlay = function(data, event) {
            var target = $(event.currentTarget);
            var bgMusic = document.getElementById('bgMusic');

            if(!bgMusic.paused) {
                bgMusic.pause();
                target.removeClass('rotate');
            }else {
                bgMusic.play();
                target.addClass('rotate');
            }
        };
        self.closeTip = function() {
            $('#make').hide();
        };

        //点击广告记录
        self.checkAdv = function (url, id) {
            var modelData = {
                adv_id: id
            };

            $.doAjax({
                url: apiUrl.checkPost,
                data: modelData,
                beforeSend: function () {
                },
                success: function(res) {
                    switch(res.code) {
                        case 1:
                            var data = res.data;

                            window.location.href = url;

                            break;
                        case 2003:
                            $.toast(res.msg, 'forbidden');
                            break;
                    }
                },
                error: function(res){
                    $.alert('系统繁忙，请刷新重试');
                }
            });
        };

        //广告商列表
        self.advPost = function () {
            var modelData = {
                activity_id: self.activity_id()
            };

            $.doAjax({
                url: 'http://huihuiba.net' + apiUrl.advPost,
                data: modelData,
                beforeSend: function () {
                },
                success: function(res) {
                    switch(res.code) {
                        case 1:
                            var data = res.data;
                            self.listAdv(data.list);

                            break;
                        case 2003:
                            $.toast(res.msg, 'forbidden');
                            break;
                    }
                },
                error: function(res){
                    $.alert('系统繁忙，请刷新重试');
                }
            });
        };

        self.ismore = ko.observable(false);
        self.ismore1 = ko.observable(false);

        self.info = ko.observableArray([
            {
                img: '/static/img/activity/freezi/13.jpg',
                ismore: false
            },
            {
                img: '/static/img/activity/freezi/23.jpg',
                ismore: false
            },
            {
            img: '/static/img/activity/freezi/51.jpg',
                ismore: false
             },
            {
                img: '/static/img/activity/freezi/32.jpg',
                ismore: true
            },
            {
                img: '/static/img/activity/freezi/43.jpg',
                ismore: false
            }
        ]);



        //加一笔
        self.supportPost = function() {
            //判断是否可以领奖
            if(self.imageNum() >= 39 && self.sign().openid == weixin_user.openid) {
                $.alert({
                    title: '集字成功',
                    text: '恭喜您完成集字活动，成功获得免学费四个月硬笔书法课程，请等待主办方联系',
                    onOK: function () {

                    }
                });
                return;
            }

            if(self.isSupport()){
                $.alert('您已写过一笔', function() {
                    //$.showShareDialog();
                });
                return;
            }
            if(self.countDown() == '活动还未开始'){
                $.toast("活动还未开始","forbidden");
                return;
            }
            if(self.countDown() == '活动已结束'){
                $.toast("活动已结束","forbidden");
                return;
            }
            if(!self.sign()){
                $.alert('您还未报名，请先报名哦', function() {
                    self.openModal();
                });
                return;
            }
            if(self.imageNum() == 39){
                $.toast("该学子已集满笔画，您无需再添一笔","forbidden");
                return false;
            }
            var modelData = {
                sign_id: signId,
                activity_id: self.activity_id()
            };

            $.doAjax({
                url: apiUrl.supportUrl,
                data: modelData,
                success: function(res) {
                    switch(res.code) {
                        case 1:
                            var data = res.data;
                            //原先使用弹框$.alert，现改为自定义弹窗
                            // self.showHelpAreaFlag(true);
                            // self.imageNum(data.sign.support_num);
                            // self.isSupport(data.is_support);
                            //
                            // if(data.is_sign) {
                            //     self.isSign(true);
                            // }
                            //
                            // self.getSignPost();

                            $.toast('成功写上一笔', 'success', function () {
                                self.imageNum(data.sign.support_num);
                                self.isSupport(data.is_support);

                                if(data.is_sign) {
                                    self.isSign(true);
                                }

                                self.getSignPost();

                            });
                           
                            break;
                        case 2003:
                            $.toast(res.msg, 'forbidden');
                            break;
                    }
                },
                error: function(res){
                    $.alert('系统繁忙，请刷新重试');
                }
            });
        };
        self.showPoster = function (){
            window.location.href = "/weixin/phantomjs/freezi/activity_id/" + self.activity_id() + "/sign_id/" + self.selfSigner().id;
        };

        self.getPost = function() {
            var modelData = {
                id: activityId,
                refresh: self.refresh()
            };

            $.doAjax({
                url: apiUrl.getJiziUrl,
                data: modelData,
                beforeSend: function () {

                },
                success: function(res) {
                    switch(res.code) {
                        case 1:
                            var data = res.data.activity;

                            self.activity(data);
                            self.signFields(data.sign_fields);
                            self.imageNum(0);
                            self.shareDefine(data.share_define);

                            self.iosMusicPlay();
                            self.share();
                            //提取校区信息
                            var campus = res.data.activity.campus;
                            self.campusArray(campus);
                            break;
                        case 2003:
                            $.toast(res.msg, 'forbidden');
                            break;
                    }
                },
                error: function(res){
                    $.alert('系统繁忙，请刷新重试');
                }
            });
        };
        self.changeInfo = function () {
            window.location.href = "/activity/freezi/signdetail?activity_id=" + self.sign().activity_id + "&sign_id=" + self.sign().id;
        };
        var first = true;
        self.getSignPost = function() {
            var modelData = {
                sign_id: signId,
                activity_id: self.activity_id(),
                refresh: 1
            };

            $.doAjax({
                url: 'http://huihuiba.net' + apiUrl.getSignUrl,
                data: modelData,
                beforeSend: function () {

                },
                success: function(res) {
                    switch(res.code) {
                        case 1:
                            var data = res.data;

                            self.imageNum(data.sign.support_num);
                            self.isSupport(data.is_support);
                            self.shareDefine(JSON.parse(data.activity.share_define));
                            data.sign.extend_info = JSON.parse(data.sign.extend_info);
                            self.sign(data.sign);
                            self.selfSigner(data.is_sign);
                            self.getCountDown(data.activity.begin_time, data.activity.end_time);

                            if(data.is_sign) {
                                self.isSign(true);
                            }


                            self.share();
                            if(first){
                                //self.activity(data.activity);
                                self.iosMusicPlay();
                                first = false;
                            }

                            if(data.sign.openid != weixin_user.openid) {
                                if(data.sign.username.length >= 4){
                                    self.helpText('帮'+ data.sign.username.slice(0,3) +'…加一笔');
                                }else {
                                    self.helpText('帮'+ data.sign.username +'加一笔');
                                }

                            }

                            //判断是否可以领奖
                            if(self.imageNum() >= self.imageTotal() && data.sign.openid == weixin_user.openid) {
                                $.alert({
                                    title: '集字成功',
                                    text: '恭喜您完成集字活动，成功获得免学费四个月硬笔书法课程，请等待主办方联系',
                                    onOK: function () {

                                    }
                                });
                            }

                            break;
                        case 2003:
                            $.toast(res.msg, 'forbidden');
                            break;
                    }
                },
                error: function(res){
                    $.alert('系统繁忙，请刷新重试');
                }
            });
        };
        self.closeModal = function() {
            $('#mask').removeClass('weui-mask--visible');
            $('#dialog').removeClass('weui-dialog--visible');
        };

        self.share = function(){
            var shareImg = 'http://' + window.location.host + '/static/img/activity/freezi/share.jpg';
            //微信分享
            wx.ready(function () {
                wx.hideOptionMenu();
                wx.showMenuItems({
                    menuList: ['menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:favorite'] // 要显示的菜单项，所有menu项见附录3
                });
                // 2.1 监听“分享给朋友”，按钮点击、自定义分享内容及分享结果接口
                wx.onMenuShareAppMessage({
                    title: self.shareDefine().title,
                    link: 'http://' + window.location.host + "/activity/freezi/index/activity_id/" + activity.id + "/sign_id/" + signId,
                    imgUrl: shareImg,
                    desc: self.shareDefine().desc, // 分享描述
                    success: function (res) {
                        self.sharePost();
                    }
                });
                //分享到朋友圈
                wx.onMenuShareTimeline({
                    title: self.shareDefine().title,
                    link: 'http://' + window.location.host + "/activity/freezi/index/activity_id/" + activity.id + "/sign_id/" + signId,
                    imgUrl: shareImg,
                    desc: self.shareDefine().desc, // 分享描述
                    success: function (res) {

                        self.sharePost();
                    }
                });
            });
        };
        self.sharePost = function(){
            var modelData = {
                activity_id: self.activity_id()
            };

            $.doAjax({
                url: apiUrl.shareUrl,
                data: modelData,
                success: function(res){
                    switch(res.code) {
                        case 1:
                            $.toast('分享成功', 'success');
                            //self.activity().share_num += 1;
                            //self.activity(self.activity());
                            $('.share-num').text(self.activity().share_num += 1);

                            break;
                        case 2003:
                            $.toast(res.msg, 'forbidden');
                            break;
                    }
                },
                error: function(res){
                    $.alert('系统繁忙，请刷新重试');
                }
            });
        };
    
        /**
         * 文字弹窗
         */
        self.closeHelpArea = function(){
            self.showHelpAreaFlag(false);
        };

        self.errors = ko.validation.group([self.username, self.mobile]);
        self.isValid = ko.computed(function() {
            return self.errors().length === 0;
        });
    };

    var viewModel = new indexViewModel();
    ko.applyBindings(viewModel);

    var init = function() {
        var agent = navigator.userAgent;
        if(signId <= 0){
            //viewModel.getPost();
            $.hideLoading();
            viewModel.getCountDown(activity.begin_time, activity.end_time);
            viewModel.share();
        }else{
            viewModel.getSignPost();
        }
        viewModel.advPost();

        //关闭弹框
        $('#pop-share').on('click', function() {
            $('#pop-share').hide();
        });

        $(function() {
            $(".lazyload").lazyload({
                threshold : 200,
                effect : "fadeIn",
                placeholder : "/static/img/activity/freezi/content.png",
            });
        });

    };

    init();
});
